import React from 'react';
import { Route, withRouter, Switch, Redirect } from 'react-router-dom';
import { observer, inject } from 'mobx-react';
import { TabPage,RouteLayout,BrowserHrm } from 'weaver-mobile-page';
import { Popover, Icon, Bubble, Tools } from 'weaver-mobile';
import { toJS } from 'mobx';
import ScheduleItem from '../calendar/schedule'
import HrmWorkplan from '../calendar/hrmWorkplan';
import Detail from '../detail/index';
import Search from '../search/index';
// import Create from '../create/index';
import RouteModal from './route';
const Item = Popover.Item;
const getLabel = Tools.getLabel;
const store = [
  'searchWorkplanStore',
  'calendarStore',
  'createStore',
];

@inject(...store)
@withRouter
@observer
export default class Workplan extends React.Component {
   constructor(props) {
    super(props);
    this.state = {
      src: Tools.mobileDetect(),
      key: 'myCalendar',
      visible: false,
      selected: '',
      span: [4, 1],
      extra: {
        // '2018-10-15': { info: true, sign: '班' },
        // '2018-10-16': { info: true, sign: { text: '休', color: 'green' } },
        // '2018-10-17': { info: true},
      },
      selectedDate: '',
      // mysubVisible: true,
      hrmVisible: true
    };
  }

  componentWillMount() {
    const {getSemanticStatus,getTabPanes,setTabs} = this.props.calendarStore;
    getSemanticStatus();
    getTabPanes();
  }
  
  componentDidMount() {
    // this.props.history.push('/calendar/myCalendar');
    let pathstr = window.location.hash && window.location.hash.split('#');
    this.setPage(pathstr[1])
    if(localStorage && localStorage.workplanTabs) {
      const pathname = this.props.location.pathname
      if(pathname.indexOf('detail') < 0){
        // let tabs = parseInt(localStorage.getItem('workplanTabs'),10);
        // this.switchTabs(tabs,tabs-1);
        // this.setState({nowTab: tabs-1,key: tabs});
      }
    }
    localStorage.removeItem('singleDetail'); // 清空刷新前的遗留数据

    if(localStorage && localStorage.getItem('newVersionSync_First') === null) {
      // 仅仅初次进入---兼容新版日程同步
      localStorage.setItem('newVersionSync_First',true);
      this.compatibleNewSync();
    }
  }


  componentWillUpdate(preProps){
    const { location: { pathname: preP }, history: h } = preProps;
    const { location: { pathname: p } } = this.props;
    const reg = /\/[^\\/]+$/;
    if (preP !== p && preP.replace(reg, '') === p.replace(reg, '') && h.action === 'POP') {
      if(window.em){
        if(p.indexOf('schedule') < 0 && p.indexOf('detail') < 0 && p.indexOf('create') < 0 && p.indexOf('search') < 0 ){
          localStorage.removeItem('selectDate');
          localStorage.removeItem('workplanTabs');
          //因为微信企业好不支持openLink,所以在打开工作台后closeWindow是连同工作台一起关闭的
          window.em.checkJsApi('openLink')&&window.em.checkJsApi('closeWindow') && window.em.closeWindow();
          !window.em.checkJsApi('openLink')&&h.go(-1);
          return false;
        }
      }
    }else{
      return true;
    }
  }

  componentWillUnmount() {
    localStorage.removeItem('workplanTabs');
    localStorage.removeItem('selectDate');
  }

  // 兼容新版日程同步
  compatibleNewSync = () => {
    const {getSyncSetting} = this.props.calendarStore;
    const initState = () => {
      // 初始化自动同步信息
        const {autoToserver,autoTomobile,} = this.props.calendarStore;
        autoTomobile === 1 ? this.setState({checked1: true}) :  this.setState({checked1: false})
        autoToserver === 1 ? this.setState({checked2: true}) :  this.setState({checked2: false})
    }

    getSyncSetting('get',initState,'','');
  }

  remindBubble = () => {
    const { mysubVisible} = this.props.calendarStore;
    Bubble.remind(!mysubVisible ? getLabel(83783,'显示下级下属'):getLabel(390066,'隐藏下级下属'),1, {top:'40%'})
  }

  handleSelect = (opt) => {
    const { getUnderlining, setState,mysubVisible } = this.props.calendarStore;
    setState({isall: 1})
    if(opt.key === '5' || opt.key === '6' || opt.key === '7') {
      opt.key === '5' && setState({OAtoLocal: 1})
      opt.key === '6' && setState({OAtoLocal: 2})
      opt.key === '7' && setState({OAtoLocal: 3})
      this.props.history.push('/calendar/myCalendar/schdulesync')
    }
    if(opt.key === '8') {
      mysubVisible ? getUnderlining({userid: '',isAll: 0}) : getUnderlining({userid: '',isAll: 1});
      this.remindBubble();
      setState({mysubVisible: !mysubVisible})
    }
    if(opt.key === '9') {
      this.props.history.push('/calendar/allCalendar/appointhrm')
    }
    this.setState({
      visible: false,
      selected: opt.props.value,
    });
  }

  handleVisibleChange = (visible) => {
    this.setState({
      visible,
    });
  };

  showSearchCondition(){
    const { history, searchWorkplanStore } = this.props;
    const { search, getConditon } = searchWorkplanStore;
    history.push(`/calendar/search`);
  }

  getHeight = () => {
    let tabPage = document.getElementsByClassName('wm-tab-page')[0];
    if(tabPage) {
      return tabPage.clientHeight;
    } 
  }

  componentWillReceiveProps (nextProps) {
    const prePath = this.props.location.pathname;
    const curPath = nextProps.location.pathname;
    if (curPath && curPath !== prePath) {
      this.setPage(curPath);
    }
  }


  setPage = (path) => {
    const set = (key) => {
      localStorage.setItem('workplanTabs',key)
      this.setState({ nowTab: key,key: key});
    }
    // let pathArr = JSON.parse(localStorage.getItem("WPTabpath"));
    // pathArr && pathArr.indexOf(path) >-1 && set(pathArr.indexOf(path)-1); 
    let { tabPanes } = this.props.calendarStore;
    tabPanes = toJS(tabPanes);
    if(Array.isArray(tabPanes)) {
      let tabObj = tabPanes.find(v => v.path === path) || {};
      tabObj.key && set(tabObj.key);
    }
  }


  switchTabs = (key,index) => {
    let pathArr = JSON.parse(localStorage.getItem("WPTabpath"))
    this.setPath(index, pathArr[key]); 

    // pathArr && pathArr.indexOf(path) >-1 && set(pathArr.indexOf(path)-1); 
    // switch(key) {
    //   case 1: this.setPath(index, '/calendar/myCalendar'); break;
    //   case 2: this.setPath(index, '/calendar/subordinate'); break;
    //   case 3: this.setPath(index, '/calendar/myFllow'); break;
    //   case 4: this.setPath(index, '/calendar/allCalendar'); break;
    //   default: ;
    // }
  }

   // 点击tab页切换
   changeTab = (tab,index) => {
    const { setState, } = this.props.calendarStore;
    localStorage.setItem('workplanTabs',tab.key); // 记录当前的tab标签
    localStorage.removeItem('userName');
    setState({isall: 0, selectDate: ''}) 
    // tab.key === 2 && getUnderlining({userid: '',isAll: 0});
    this.setState({key: tab.key, nowTab: tab.key})
    // this.switchTabs(tab.key,index)
    this.setPath('', tab.path);
  }

  setPath = (key, path) => {
    this.props.history.push(path);
  }

  appontHRM = (arg) => {
    const { changeUserInfo} = this.props.calendarStore;
    changeUserInfo(arg[0],arg[1]);
    localStorage.setItem('userName',arg[1])
    localStorage.setItem('userId',arg[0])
    setTimeout(() => {// 卸载browserHrm组件后跳转至schdule页面
      this.setState({hrmVisible: false})
      arg[0] !== '' && this.props.history.push('/calendar/appointhrm/schdule')
      arg[0] === '' && this.props.history.push('/calendar/allCalendar')
    }, 200);
  }

  showPopover = () => {
    const { key, src} = this.state;
    if(parseInt(key,10) === 2 || parseInt(key,10) === 4) {
      return true;
    }else if(src.isEmobile() && parseInt(key,10) === 1) {
      return true;
    }else{
      return false;
    }
  }

  showPopoverNew = () => {
    const { key, src} = this.state;
    if(key === 'subordinate' || key === 'allCalendar') {
      return true;
    }else if(src.isEmobile() && key === 'myCalendar') {
      return true;
    }else{
      return false;
    }
  }

  render() {
    const { hrmBrowser,mysubVisible,semanticStatus,isInit,tabPanes,setState1,getTabPanes} = this.props.calendarStore;
    const { searchLayout,} = this.props.searchWorkplanStore;
    // const { createLayout,} = this.props.createStore;

    const tabs = [
      { title: getLabel(18480,'我的日程'),key:1, path:'/calendar/myCalendar'},
      { title: getLabel(386548,'下属日程'),key:2, path:'/calendar/subordinate'},
      { title: getLabel(26469,'我的关注'),key:3, path:'/calendar/myFllow'},
      { title: getLabel(27910,'所有日程'),key:4, path:'/calendar/allCalendar'}
    ];
    if(tabPanes.length == 0 && JSON.parse(localStorage.getItem("WPBaseTabs"))){
      setState1({tabPanes:JSON.parse(localStorage.getItem("WPBaseTabs"))})
    }
    const btns= [
        <Icon type="filter-o" onClick={this.showSearchCondition.bind(this)}/>,
    ];
    const {span,visible,key,} = this.state;
    // const overlay= [
    //     (parseInt(key,10) === 1 &&<Item key='5' value="oa2local">{getLabel(391130,'OA同步日程到本地')}</Item>),
    //     (parseInt(key,10) === 1 &&<Item key='6' value="local2oa" style={{ whiteSpace: 'nowrap' }}>{getLabel(391131,'本地同步日程到OA')}</Item>),
    //     (parseInt(key,10) === 1 &&<Item key='7' value="localset" style={{ whiteSpace: 'nowrap' }}>{getLabel(391132,'日程自动同步设置')}</Item>),
    //     (parseInt(key,10) === 2 && <Item key='8' value="sub-sub" style={{ whiteSpace: 'nowrap' }} >{!mysubVisible ? getLabel(83783,'显示下级下属'):getLabel(390066,'隐藏下级下属')}</Item>),
    //     (parseInt(key,10) === 4 && <Item key='9' className='allCalendarItem' value="appoint-hrm" style={{ whiteSpace: 'nowrap' }} >
    //                     {getLabel(391082,'按指定人员查看')}
    //                   </Item>),
    // ];
    const overlay= [
      (key === "myCalendar" &&<Item key='5' value="oa2local">{getLabel(391130,'OA同步日程到本地')}</Item>),
      (key === "myCalendar" &&<Item key='6' value="local2oa" style={{ whiteSpace: 'nowrap' }}>{getLabel(391131,'本地同步日程到OA')}</Item>),
      (key === "myCalendar" &&<Item key='7' value="localset" style={{ whiteSpace: 'nowrap' }}>{getLabel(391132,'日程自动同步设置')}</Item>),
      (key === "subordinate" && <Item key='8' value="sub-sub" style={{ whiteSpace: 'nowrap' }} >{!mysubVisible ? getLabel(83783,'显示下级下属'):getLabel(390066,'隐藏下级下属')}</Item>),
      (key === "allCalendar" && <Item key='9' className='allCalendarItem' value="appoint-hrm" style={{ whiteSpace: 'nowrap' }} >
                      {getLabel(391082,'按指定人员查看')}
                    </Item>),
    ];
    const popoverProps = {
      visible,
      overlay,
      onSelect: this.handleSelect,
      onVisibleChange: this.handleVisibleChange,
    };
    
    const tabProps = {
      onChange: (tab,index) => { this.changeTab(tab,index) },
      page:this.state.nowTab
    };
    return (
      <div className="calendar-schdule">
        {<div className="calendar-schdule-browserhrm">
          {/* 所有日程-查看指定人员日程时,为了使用browserHrm组件,只能将其隐藏,才能卸载改组件 */}
          <BrowserHrm
            className="meeting-calendar-schdule-browserhrm"
            label={getLabel(391082,'按指定人员查看')}
            store={hrmBrowser}
            type={17}
            isSingle={true}
            onChange={(...arg) => {this.appontHRM(arg)}}
          >
          </BrowserHrm>
        </div>}
        <TabPage
          btns={btns}
          span={span}
          tabs={tabPanes}
          tabProps={tabProps}
          popover={this.showPopoverNew()}
          popoverProps={popoverProps}
          className="workplan-tabs"
        />
        <div className="tab-page">
          <Switch>
            <Route
              key="myCalendar"
              path="/calendar/myCalendar"
              render={()=>(
                <div id="myCalendar" style={{height: '100%'}}>
                  {/* 我的日程 */}
                  <ScheduleItem isInit={isInit} semanticStatus={semanticStatus} type={'myCalendar'} tabHeight={'45'}/>
                </div>
              )}
            />
            <Route
              key="subordinate"
              path="/calendar/subordinate"
              render={()=>(
                <div id="subordinate">
                  {/* 我的下属 */}
                  <HrmWorkplan type={'mySub'} />
                </div>
              )}
            />
            <Route
              key="myFllow"
              path="/calendar/myFllow"
              render={()=>(
                <div id="myFllow">
                  {/* 我的关注 */}
                  <HrmWorkplan type={'myFllow'} />
                </div>
              )}
            />
            <Route
              key="allCalendar"
              path="/calendar/allCalendar"
              render={()=>(
                <div id="subordinate" style={{height: '100%'}}>
                  {/* 所有日程 */}
                  <ScheduleItem isInit={isInit} semanticStatus={semanticStatus} type={'allCalendar'} tabHeight={'45'} />
                </div>
              )}
            />
            <Route
              key="workplanDetail"
              path="/calendar/:type/detail" // 匹配： calendar/.../detail  格式的路由地址
              render={()=>(
                <RouteLayout>
                <div key="calendarDetail" className="wm-route-layout wm-demo-route-layout-page">
                  <Detail />
                </div>
                </RouteLayout>
              )}
            />
             <Route
              key={searchLayout.id}
              path={searchLayout.path}
              render={()=>(
                <RouteLayout>
                <div key="calendarDetail" className="wm-route-layout wm-demo-route-layout-page">
                  <Search />
                </div>
                </RouteLayout>
              )}
            />
            {/* <Route
              key={createLayout.id}
              path={createLayout.path}
              render={()=>(
                <RouteLayout>
                <div key="calendarDetail" className="wm-route-layout wm-demo-route-layout-page">
                  <Create />
                </div>
                </RouteLayout>
              )}
            /> */}
       
            <Redirect exact path="/calendar" to={{pathname: '/calendar/myCalendar'}} />
          </Switch>
        </div>
        <RouteModal />
      </div>
    );
  }
}